package cn.gjxblog.common.aspect;

import cn.gjxblog.common.annotation.SysLog;

import cn.gjxblog.modules.sys.entity.SysLogEntity;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Author guojiaxun
 * @Date 2019/9/9 19:05
 */
@Slf4j
@Aspect
@Component
public class SysLogAspect {

    @Pointcut("@annotation(cn.gjxblog.common.annotation.SysLog)")
    public void logPointCut(){
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object proceed = point.proceed();
        //执行时长
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        saveSysLog(point, time);

        return proceed;
    }

    private void saveSysLog(ProceedingJoinPoint point, long time) {
        MethodSignature signature = (MethodSignature)point.getSignature();
        Method method = signature.getMethod();

        SysLogEntity sysLogEntity = new SysLogEntity();
        SysLog sysLog = method.getAnnotation(SysLog.class);
        if(sysLog != null){
            sysLogEntity.setOperation(sysLog.value());
        }
        //请求的方法名
        String className = point.getTarget().getClass().getName();
        
        String methodName = signature.getName();
        sysLogEntity.setMethod(className + "." + methodName + "()");

        //请求的参数
        Object[] args = point.getArgs();
        String param = JSONObject.toJSONString(args);
        sysLogEntity.setParams(param);

        //获取请求的ip
        //HttpConte

        //设置耗时
        sysLogEntity.setTime(time);

        //设置创建时间
        sysLogEntity.setCreateDate(new Date());

        log.info("对象为：" + sysLogEntity);
    }

}
